<script setup lang="ts">
import { getRoleListApi } from "@/api/role";
import { updateRole } from "@/api/user";
import {  onMounted, ref } from "vue";

const visible = ref(false);

const userFormRef = ref();
const roleData = ref([]);
const treeRef = ref<any>();

class UserRoleFOrm {
  id = "";
  roles = [];
}

const userRoleForm = ref(new UserRoleFOrm());

const open = (id: string = "") => {
  visible.value = true;
  userRoleForm.value = new UserRoleFOrm();
  setTimeout(() => {
    if (id) {
      userRoleForm.value.id = id;
    }
  });
};

// 获取角色
const getRole = async () => {
  const ret = await getRoleListApi();
  roleData.value = ret;
};

onMounted(() => {
  getRole();
});

const beforeClose = (deno: any) => {
  deno();
};

const updateUser = async () => {
  const roleList = treeRef.value.getCheckedKeys();
  userRoleForm.value.roles = roleList;
  console.log(userRoleForm.value);
  const ret = await updateRole(userRoleForm.value);
  console.log(ret);
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    :before-close="beforeClose"
    v-model="visible"
    title="用户角色"
    :with-header="false"
  >
    <el-form
      ref="userFormRef"
      label-position="left"
      label-width="auto"
      :model="userRoleForm"
      style="max-width: 600px"
    >
      <el-form-item prop="id" label="用户id">
        <el-input v-model="userRoleForm.id"></el-input>
      </el-form-item>
      <el-form-item prop="roles" label="用户角色">
        <el-tree
          ref="treeRef"
          :data="roleData"
          show-checkbox
          node-key="id"
          :props="{ label: (data) => data.name }"
        />
      </el-form-item>
    </el-form>
    <template #footer v-slot="scope">
      <div class="drawer-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped lang="less"></style>
